<?php

function addfinance($uid, $amount, $currency, $type, $finadesc = '', $finacode = '', $commit = 1, $link = '') {
//$amoun:金额,  $type:1.加，2.扣 ,  $finadesc:财务描述
    //判断额度合法性
    if (!is_numeric($amount) || $amount <= 0) {
        return false;
    }
    $amount = (float) $amount;
    //判断操作类型合法性
    if (!in_array($type, array(1, 2))) {
        return false;
    }
    switch ($currency) {
        case 1: $field = 'jc';
            break;
        case 2: $field = 'jP';
            break;
        case 3: $field = 'zeng';
            break;
        default:return false;
    }
    if ($link == '') {
        $dblink = getdblink();
    } else {
        $dblink = $link;
    }

    $sql = "select {$field}_cash,appid from userinfo where id=$uid";
    $userinfo = getonerecord_ps($sql, $dblink);
    //判断用户是否存在
    if (!$userinfo) {
        return false;
    }
    $userinfo_tb = "userinfo";
    exec_db_ps("LOCK TABLE $userinfo_tb WRITE", $dblink);
    $current_cash = $userinfo[$field . '_cash'];
    if ($type == 1) {
        $current_ext = $current_cash + $amount;
        $sql = "update $userinfo_tb set {$field}_cash={$field}_cash+$amount,{$field}_history_cash={$field}_history_cash+$amount where id=$uid";
    } else {
        if ($current_cash < $amount) {
            return false;
        }
        $current_ext = $current_cash - $amount;
        $sql = "update $userinfo_tb set {$field}_cash={$field}_cash-$amount where id=$uid";
    }
    $issuccess = exec_db_ps($sql, $dblink);
    exec_db_ps("unlock tables", $dblink);
    if (!$issuccess) {
        return false;
    }

    $ip = getip();
    $area = getiparea($ip);
    $time = time();
    $appid = $userinfo['appid'];
    $insertsqlL = "uid,currency,amount,ext_cash,type,ip,area,ontime,appid";
    $insertsqlR = "$uid,$currency,$amount,$current_ext,$type,'$ip','$area',$time,$appid";
    if ($finadesc) {
        $insertsqlL .= ",finadesc";
        $insertsqlR .= ",'$finadesc'";
    }
    if ($finacode) {
        $insertsqlL .= ",finacode";
        $insertsqlR .= ",'$finacode'";
    }
    $sql = "insert into finance ($insertsqlL) values ($insertsqlR);";
    if ($commit == 1) {
        exec_db($sql);
    } else {
        exec_db_ps($sql, $dblink);
    }
    return true;
}

function inputFilter($str) {
    if (empty($str)) {
        return;
    }
    if ($str == "") {
        return $str;
    }
    $str = trim($str);
    $str = str_replace("&", "&amp;", $str);
    $str = str_replace(">", "&gt;", $str);
    $str = str_replace("<", "&lt;", $str);
    $str = str_replace(chr(34), "&", $str);
    $str = str_replace(chr(39), "&#39;", $str);
    $str = str_replace(chr(13), "<br />", $str);
    $str = str_replace("'", "''", $str);
    $str = str_replace("select", "sel&#101;ct", $str);
    $str = str_replace("join", "jo&#105;n", $str);
    $str = str_replace("union", "un&#105;on", $str);
    $str = str_replace("where", "wh&#101;re", $str);
    $str = str_replace("insert", "ins&#101;rt", $str);
    $str = str_replace("delete", "del&#101;te", $str);
    $str = str_replace("update", "up&#100;ate", $str);
    $str = str_replace("like", "lik&#101;", $str);
    $str = str_replace("drop", "dro&#112;", $str);
    $str = str_replace("create", "cr&#101;ate", $str);
    $str = str_replace("modify", "mod&#105;fy", $str);
    $str = str_replace("rename", "ren&#097;me", $str);
    $str = str_replace("alter", "alt&#101;r", $str);
    $str = str_replace("cast", "ca&#115;", $str);
    return $str;
}

function getip() {
    $ip = false;
    if (!empty($_SERVER ["HTTP_CLIENT_IP"])) {
        $ip = $_SERVER ["HTTP_CLIENT_IP"];
    }
    if (!empty($_SERVER ['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(", ", $_SERVER ['HTTP_X_FORWARDED_FOR']);
        if ($ip) {
            array_unshift($ips, $ip);
            $ip = FALSE;
        }
        for ($i = 0; $i < count($ips); $i ++) {
            if (!preg_match("/^(10|172\.16|192\.168)\./i", $ips[$i])) {
                $ip = $ips[$i];
                break;
            }
        }
    }
    $ip_str = ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    $ip_arr = explode(',', $ip_str);
    return $ip_arr[0];
}

function randomkeys($length) {
    $key = null;
    $pattern = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ";
    for ($i = 0; $i < $length; $i ++) {
        $key .= $pattern {mt_rand(0, 35)};
    }
    return $key;
}

function getinsertsql($table_name, $field_array) {
    $field_str = '';
    $value_str = '';
    foreach ($field_array as $key => $value) {
        $field_str .= "`$key`,";
        $value_str .= "'$value',";
    }
    $field_str = rtrim($field_str, ',');
    $value_str = rtrim($value_str, ',');
    return "INSERT INTO $table_name($field_str) VALUES($value_str)";
}

function sqlupdate($table_name, $field_array, $where) {
    $field_str = '';
    foreach ($field_array as $key => $value) {
        $field_str .= "`$key`='{$value}',";
    }
    $field_str = rtrim($field_str, ',');
    return "UPDATE {$table_name} SET {$field_str} WHERE {$where}";
}

function exec_db($query_str) {
    $dblink = new mysqli(DBHOST, DBUSER, DBPWD, DBNAME);
    if ($dblink->connect_error) {
        echo "connect db error";
        exit;
    }
    $dblink->query("set names UTF8");
    $result = $dblink->query($query_str);
    if (!$result) {
        writelog('sql_wrong.txt', $query_str . ' ' . $dblink->error);
        die("Query failed:" . mysqli_error($dblink));
    }
    mysqli_close($dblink);
    return $result;
}

function getonerecord($query_str) {
    $result = exec_db($query_str);
    $row = $result->fetch_assoc();
    mysqli_free_result($result);
    return $row;
}

function getdblink() {
    $dblink = new mysqli(DBHOST, DBUSER, DBPWD, DBNAME);
    if ($dblink->connect_error) {
        echo "connect db error";
        exit;
    }
    $dblink->query("set names UTF8");
    return $dblink;
}

function getonerecord_ps($query_str, $dblink) {
    $result = exec_db_ps($query_str, $dblink);
    $row = $result->fetch_assoc();
    mysqli_free_result($result);
    return $row;
}

function exec_db_ps($query_str, $dblink) {
    $result = $dblink->query($query_str);
    if (!$result) {
        writelog('sql_wrong_ps.txt', $query_str . ' ' . $dblink->error);
        die("Query failed:");
    }
    return $result;
}

function last_insert_ps($query_str, $dblink) {
    $result = $dblink->query($query_str);
    if (!$result) {
        writelog('sql_wrong_ps.txt', $query_str . ' ' . $dblink->error);
        die("Query failed:");
    }
    return $dblink->insert_id;
}

function getallrecord($query_str) {
    $result = exec_db($query_str);
    $data = $result->fetch_all(MYSQLI_ASSOC);
    mysqli_free_result($result);
    return $data;
}

function init_smarty() {
    include_once(S_ROOT . "source/libs/Smarty.class.php");
    $tpl = new Smarty();
    $tpl->template_dir = S_ROOT . "templates/";
    $tpl->compile_dir = S_ROOT . "templates_c/";
    $tpl->cache_dir = S_ROOT . "cache/";
    $tpl->left_delimiter = '<!--{';
    $tpl->right_delimiter = '}-->';
    return $tpl;
}

function getiparea($ip) {
    include_once(S_ROOT . "source/ip/qqwry.php");
    $QQWry = new QQWry;
    $QQWry->qqwrys($ip);
    $area = trim($QQWry->Country);
    $area = gbktoutf($area);
    if ($area == "局域网") {
        $area = "中国";
    }
    return $area;
}

function echojson($msg = '', $status = 0, $dataarr = array()) {
    if (empty($dataarr)) {
        $dataarr = array();
    }
    $arr = array(
        'msg' => $msg,
        'status' => $status . '',
        'data' => $dataarr
    );
    return json_encode($arr);
}

/**
 * 获得memcache对象
 */
function get_memcache($server_id) {
    $server_id = (int) $server_id;
    switch ($server_id) {
        case 0:$server = MEMCACHE_HOST_0;
            $port = MEMCACHE_PORT_0;
            break;
        default:;
            break;
    }
    $memcache_obj = memcache_connect($server, $port);
    return $memcache_obj;
}

function gbktoutf($string) {
    $string = charset_encode("gb2312", "utf-8", $string);
    return $string;
}

function charset_encode($_input_charset, $_output_charset, $input) {
    $output = "";
    $string = $input;
    if (is_array($input)) {
        $key = array_keys($string);
        $size = sizeof($key);
        for ($i = 0; $i < $size; $i ++) {
            $string [$key [$i]] = charset_encode($_input_charset, $_output_charset, $string [$key [$i]]);
        }
        return $string;
    } else {
        if (!isset($_output_charset))
            $_output_charset = $_input_charset;
        if ($_input_charset == $_output_charset || $input == null) {
            $output = $input;
        } elseif (function_exists("mb_convert_encoding")) {
            $output = mb_convert_encoding($input, $_output_charset, $_input_charset);
        } elseif (function_exists("iconv")) {
            $output = iconv($_input_charset, $_output_charset, $input);
        } else
            die("sorry, you have no libs support for charset change.");
        return $output;
    }
}

function addpaymoney($ordernum, $charge_cashs, $trade_no = '') {
    $charge_cash = doubleval($charge_cashs);
    $sql = "select * from orders where ordernum='$ordernum' and dstatus=0 limit 1";
    $row = getonerecord($sql);
    if ($row) {
        $uid = $row["uid"];
        //$paytype = $row["paytype"];
        $money = doubleval($row["money"]);
        $gift_id = $row["gift_id"];
        if ($money != $charge_cash) {
            $row['now_cash'] = $charge_cashs;
            //writelog('支付金额和下单金额不一致', $row);
            return false;
        }
        
        /*if ($paytype == 1) {
          $finadesc = '支付宝购买' . $gift_name;
          } elseif ($paytype == 2) {
          $finadesc = '微信购买' . $gift_name;
          } else {
          $finadesc = '其他方式购买' . $gift_name;
          } */
        $finadesc = '赠送金币';
        if ($gift_id == 100) {
            //新手充6元得1000金币和10个666活动     
            $gift_num = 10;
            $jc_cash = 1000;
        } else {
            include S_ROOT . '/source/data/gift.php';     
            //$gift_name = $gift[$gift_id]['name'];
            $gift_num = $gift[$gift_id]['num'];
            $jc_cash = $charge_cash * 100;           
        }

        $sql_day = "update orders set dstatus=1,trade_no='$trade_no' where ordernum='$ordernum'";
        exec_db($sql_day);
        addfinance($uid, $jc_cash, 1, 1, $finadesc, $ordernum, $commit = 1, $link = '');
        $lbinfo = getonerecord("select id,num from gifts_user where uid='$uid' and gift_id='$gift_id' limit 1");
        if (!$lbinfo) {
            exec_db("INSERT INTO gifts_user (uid,gift_id,num) VALUES ('$uid','$gift_id','$gift_num')");
        } else {
            exec_db("update gifts_user set num=num+'$gift_num' where  uid='$uid' and gift_id='$gift_id'");
        }
        return true;
    } else {
        writelog('updateorders', $ordernum);
        return false;
    }
}

function addpayorder($uid, $money, $paytype, $pttype, $sign, $ver, $buytype, $giftid, $payfrom) {
    $t_sign = md5($uid . $money . $paytype . $pttype . KEY);
    if ($sign != $t_sign) {
        return echojson('sign error', 0, '');
    }
    if (!$uid) {
        return echojson('uid is not find ', 0, '');
    }

    if (!is_numeric($money) || $money < 1) {
        return echojson('money error', 0, '');
    }
    $limit = op_limit("ttdb_addorders_{$uid}", 3);
    if ($limit) {
        return echojson("frequent operation", 0, '');
    }
    $sql = "select username,channel,ontime,pt,appid from userinfo where id=$uid limit 1";
    $row = getonerecord($sql);
    if ($row) {
        $umstat = $row["channel"];
        $appid = $row["appid"];
        $ip = getip();
        $ontime = time();
        $ordernum = $appid . date('Ymd') . randomkeys(5) . date('His') . randomkeys(5);
        $sql_day = "insert into orders(uid,ver,paytype,pttype,buytype,ordernum,ontime,ip,money,dstatus,appid,issave,umstat,gift_id,payfrom) values('$uid','$ver','$paytype','$pttype','$buytype','$ordernum','$ontime','$ip','$money','0','$appid','0','$umstat','$giftid','$payfrom')";
        exec_db($sql_day);
        $data = array("ordernum" => $ordernum, 'ip' => $ip);
        return echojson('', 1, $data);
    }
}

function writelog($file, $content) {
    file_put_contents(S_ROOT . "cache/{$file}", date('Y-m-d H:i:s') . ':' . $content . "\r\n", FILE_APPEND);
}

/**
 * 操作间隔限制,受限返回真
 */
function op_limit($key, $timeout) {
    $res = false;
    $memcache_obj = get_memcache(0);
    $op_time = memcache_get($memcache_obj, $key);
    if ($op_time === false) {
        memcache_add($memcache_obj, $key, 1, 0, $timeout);
    } else {
        $res = true;
    }
    return $res;
}

/**
 * 操作次数限制,受限返回真
 */
function op_numlimit($key, $times, $timeout) {
    $res = false;
    $memcache_obj = get_memcache(0);
    $op_time = memcache_get($memcache_obj, $key);
    ;
    if ((int) $op_time >= $times) {
        return true;
    }
    if ($op_time === false) {
        memcache_add($memcache_obj, $key, 1, 0, $timeout);
    } else {
        memcache_increment($memcache_obj, $key);
    }
    return $res;
}
